<?php
/**
 * Created by PhpStorm.
 * User: serenehaly
 * Date: 2018/2/7
 * Time: 17:41
 */

namespace app\api\service;


use app\lib\exception\TokenException;
use think\Cache;
use think\Exception;
use think\Request;

class Token
{
    // 生成token令牌
    public static function generateToken()
    {
        $randChar = get_rand_char(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $tokenSalt = config('secure.token_salt');
        return md5($randChar . $timestamp . $tokenSalt);
    }

    public static function getCurrentTokenVal($key)
    {
        $token = Request::instance()->header('token');
        $value = Cache::get($token);
        if ($value) {
            if (!is_array($value)) {
                $value = json_decode($value, true);
            }
            if (array_key_exists($key, $value)) {
                return $value[$key];
            } else {
                throw new Exception('token所对应的值不存在该变量');
            }
        } else {
            throw new TokenException();
        }
    }

    public static function getCurrentUid()
    {
        $uid = self::getCurrentTokenVal('uid');
        return $uid;
    }
}